<template>
  <div>
    <PanelSplitTwo bottomToolbarHeight="0" :num="2">
    <template #top>
      <!-- <SetUserSelect
        :key="keys"
        class="queryForm"
        :formData="orderSelect"
        v-model:queryParams="paginationParams"
        @selectFunc="selectFunc"
      ></SetUserSelect> -->
      <el-form
          ref="formRefmin"
          :model="paginationParams"
          label-width="100px"
          class="demo-ruleForm"
        >
        <div style="display: flex;flex-wrap: wrap;">
          <el-form-item
            label="代理商"
          >
            <el-select v-model="paginationParams.agencyId" placeholder="请选择代理商" style="width: 200px">
              <el-option v-for="(item, index) in getagencyList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="品种"
          >
            <el-select v-model="paginationParams.drugId" placeholder="请选择品种" style="width: 200px">
              <el-option v-for="(item, index) in getdrugList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="省份"
          >
            <el-select @change="changProvinceFun" v-model="paginationParams.province" placeholder="请选择省份" style="width: 200px">
              <el-option v-for="(item, index) in getgetprovinceList" :key="index" :label="item.cityname" :value="item.cityname" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="城市"
          >
            <el-select v-model="paginationParams.city" placeholder="请选择城市" style="width: 200px">
              <el-option v-for="(item, index) in getcityList" :key="index" :label="item.cityname" :value="item.cityname" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="年份"
          >
            <el-select v-model="paginationParams.year" placeholder="请选择年份" style="width: 200px">
              <el-option v-for="(item, index) in yearList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="月份"
          >
            <el-select v-model="paginationParams.month" placeholder="请选择月份" style="width: 200px">
              <el-option v-for="(item, index) in monthList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="状态"
          >
            <el-select v-model="paginationParams.status" placeholder="请选择状态" style="width: 200px">
              <el-option v-for="(item, index) in finRepor_sta_type" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;width: 100%;justify-content: flex-end;">
              <el-button type="primary" @click="submitFormmin">搜索</el-button>
              <el-button @click="resetFormmin(formRefmins)">重置</el-button>
            </div>
          </el-form-item>
        </div>
         
        </el-form>
    </template>
     <template #centerToolbar>
        <div class="vex_flex">
          <el-row :gutter="20" style="margin-bottom: 10px">
            <el-col :span="1.5">
              <el-button @click="handleQuery">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="getMakeFun">生成</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="handlereport">手动生成</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="delFun">删除</el-button>
            </el-col>
          </el-row>
        <VxeTableGrid
          :key="keys"
          style="flex: 1;"
          :tableColumn="tableColumn"
          :tableLoading="tableLoading"
          :dataList="dataList"
          :showPagination="true"
          :paginationParams="paginationParams"
          @getList="setQueryParams"
          @selectedChange="selectedChange"
        >
        </VxeTableGrid>
      </div>
      <el-dialog v-model="dialogFormVisible" title="新增分析报告">
        <el-form
          ref="formRef"
          :model="numberValidateForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="代理商"
            prop="agencyId"
            :rules="[
              { required: true, message: '请选择代理商' },
            ]"
          >
            <el-select v-model="numberValidateForm.agencyId" placeholder="请选择代理商" style="width: 400px">
              <el-option v-for="(item, index) in getagencyList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="品种"
            prop="drugId"
            :rules="[
              { required: true, message: '请选择品种' },
            ]"
          >
            <el-select  v-model="numberValidateForm.drugId" placeholder="请选择品种" style="width: 400px">
              <el-option v-for="(item, index) in getdrugList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="省份"
            prop="province"
            :rules="[
              { required: true, message: '请选择省份' },
            ]"
          >
            <el-select filterable @change="changProvinceFun" v-model="numberValidateForm.province" placeholder="请选择省份" style="width: 400px">
              <el-option v-for="(item, index) in getgetprovinceList" :key="index" :label="item.cityname" :value="item.cityname" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="城市"
            prop="city"
            :rules="[
              // { required: true, message: '请选择城市' },
            ]"
          >
            <el-select filterable  multiple  v-model="numberValidateForm.city" placeholder="请选择城市" style="width: 400px">
              <el-option v-for="(item, index) in getcityList" :key="index" :label="item.cityname" :value="item.cityname" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="年份"
            prop="year"
            :rules="[
              { required: true, message: '请选择年份' },
            ]"
          >
            <el-select v-model="numberValidateForm.year" placeholder="请选择年份" style="width: 400px">
              <el-option v-for="(item, index) in yearList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="月份"
            prop="month"
            :rules="[
              { required: true, message: '请选择月份' },
            ]"
          >
            <el-select v-model="numberValidateForm.month" placeholder="请选择月份" style="width: 400px">
              <el-option v-for="(item, index) in monthList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="调整比例(%)"
            prop="percentage"
            :rules="[
              { required: true, message: '请输入调整比例' },
            ]"
          >
            <el-input-number placeholder="请输入调整比例(%)" style="width: 400px;text-align: left;" controls-position="right" v-model="numberValidateForm.percentage" :min="0" :max="100" />
          </el-form-item>
          <!-- <el-form-item
            label="日期"
            prop="value2"
            :rules="[
              { required: true, message: '请选择日期' },
            ]"
          >
            <el-date-picker
              style="width: 400px"
              v-model="numberValidateForm.value2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item> -->
          <el-form-item>
            <div style="display: flex;width: 100%;justify-content: flex-end;">
              <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
              <el-button @click="resetForm(formRef)">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
     </template>
   </PanelSplitTwo>

  </div>
  
</template>
<script setup name="DepartmentList" lang="jsx">
import { useRouter, useRoute } from 'vue-router'
import { agencyList } from "@/api/basicManagement/agencyMana";
import { drugList  } from "@/api/basicManagement/varietyMana";
import { getprovince, getcity } from "@/api/basicManagement/hospital";
import { getfinReportList as getList, addsystemmessage, upsystemmessage, messageById, addfinReport, getMake, exportHandle, finReportexport, byFinReportId } from "@/api/basicManagement/information";
import { ElMessageBox } from 'element-plus';
import datas from './data.js'
const { proxy } = getCurrentInstance();
const { set_year_time, set_moon_time, finRepor_sta_type } = proxy.useDict("set_year_time", "set_moon_time", "finRepor_sta_type");
const route = useRoute();

const keys = ref(0)
const Id = ref('')
const { paginationParams, orderSelect, addorderSelect, addpaginationParams }  = datas
const tableColumn = ref([
  { type: "checkbox", width: 60, fixed: null },
  { field: "agencyName", title: "代理商" },
  { field: "drugName", title: "品种" },
  { field: "province", title: "省份" },
  { field: "city", title: "城市" },
  { field: "year", title: "年份" },
  { field: "month", title: "月份" },
  { field: "createTime", title: "创建时间" },
  { field: "status", title: "状态",
  slots: { default: ({ row }, h) => {
    return [<dict-tag options={ finRepor_sta_type.value } value={ row.status }></dict-tag>]
  }} }
])


const router= useRouter ()



const pageSize = ref(10);
let tableLoading = ref(false)
const dataList = ref([
])

// 切换分页
  function setQueryParams(val) {
    paginationParams.value.pageNum = val.pageNum;
    paginationParams.value.pageSize = val.pageSize;
    getListFun()
  }
  // 选择表格
  let selectedList = ref([])
  function selectedChange(val) {
    Id.value = val.currentItem.id
    selectedList.value = val.selectedList
    // this.form.customerId = val.currentItem.customerId;
  }
/** 搜索按钮操作 */
let types = ref('')
function handleQuery(type) {
  addpaginationParams.value = {
    userIdList: [],
  }
  types.value = type
  dialogFormVisible.value = true
 
  type == 1 && messageById(Id.value).then((res) => {
    res.data.userIdList = [res.data.userId]
    addpaginationParams.value = res.data
  })
}
const getListFun = () => {
  getList({
    ...paginationParams.value,
    isDeleted: 0
  }).then((res) => {
    dataList.value = res.rows
    paginationParams.value.total = res.total
    selectedList.value = []
    keys.value = new Date().getTime()
  })
}

getListFun()
const selectFunc = () => {
  paginationParams.value.pageNum = 1
  getListFun()
}
const delFun = () => {
  ElMessageBox.confirm('是否确认删除?')
    .then(() => {
      byFinReportId(Id.value).then(() => {
        proxy.$modal.msgSuccess(`删除成功`);
        getListFun()
      })
    })
    .catch(() => {
      // catch error
    })
  
}
const dialogFormVisible = ref(false)
const dialogFormVisibleFun  = () => {
  if (types.value == 1) {
    dialogFormVisible.value = false
    return
  }
  proxy.$refs.setUserSelect.submitForm().then((val) => {
    addsystemmessage({
      ...val
    }).then(() => {
      proxy.$modal.msgSuccess(`新增成功`);
      dialogFormVisible.value = false
      getListFun()
    })
  })
}


const formRef = ref('formRef')

const numberValidateForm = reactive({
  region: '',
})
const formRefmins = ref('formRefmin')
const resetFormmin = (formEl) => {
  paginationParams.value = {
    pageNum: 1,
    pageSize: 10,
  }
  getListFun()
}
const resetForm = (formEl) => {
  dialogFormVisible.value= false
  if (!formEl) return
  formEl.resetFields()
}
function getMonthSE(date) {
  let nowdays = date ? new Date(date) : new Date();
  let year = nowdays.getFullYear();
  let month = nowdays.getMonth() + 1;
 
  if (month < 10) { month = "0" + month; }
 
  let myDate = new Date(year, month, 0);
 
  let startDate = year + "-" + month + "-01" + ' ' + '00:00:00';
  let endDate = year + "-" + month + "-" + myDate.getDate() + ' ' + '23:59:59';
 
  return [startDate, endDate];
}
const submitForm = (formEl) => {
  // console.log(getMonthSE(numberValidateForm.year + '-' + numberValidateForm.month + '-' + 1))

  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      addfinReport({
        ...numberValidateForm,
        startTime: getMonthSE(numberValidateForm.year + '-' + numberValidateForm.month + '-' + 1)[0],
        endTime: getMonthSE(numberValidateForm.year + '-' + numberValidateForm.month + '-' + 1)[1],
        agencyName: getagencyList.value.filter(item => item.id == numberValidateForm.agencyId)[0].name,
        drugName: getdrugList.value.filter(item => item.id == numberValidateForm.drugId)[0].name,
        city: numberValidateForm.city && numberValidateForm.city.join(',')
      }).then((res) => {
        proxy.$modal.msgSuccess(`新增成功`);
        dialogFormVisible.value = false
        formEl.resetFields()
        getListFun()
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const getagencyList = ref([])
const agencyListFun = () => {
  agencyList({
    isDeleted: 0,
    status: 4
  }).then((res) => {
    
    getagencyList.value = res.rows
  })
}
const getdrugList = ref([])
const drugListFun = () => {
  drugList().then((res) => {
    getdrugList.value = res.rows
  })
}


const getgetprovinceList = ref([])
const getprovinceFun = () => {
  getprovince().then((res) => {
    getgetprovinceList.value = res.data
  })
}
const getcityList = ref([])
const getcityFun = (pid) => {
  getcity(pid).then((res) => {
    getcityList.value = res.data
  })
}

const changProvinceFun = (e) => {
  numberValidateForm.city = []
  getcityFun(getgetprovinceList.value.filter(item => item.cityname == e)[0].id)
}
const yearList = ref([])
watch(
  set_year_time,
  (newV, oldV) => {
    // yearList
    yearList.value = set_year_time.value
  }
);
const monthList = ref([])
watch(
  set_moon_time,
  (newV, oldV) => {
    // 
    monthList.value = set_moon_time.value
  }
);


const getMakeFun = () => {
  getMake({
    id: Id.value
  }).then(() => {
    proxy.$modal.msgSuccess(`生成成功`);
    getListFun()
  })
}

function uploadFile(blob, filename) {
  const a = document.createElement("a");
  let href;
  // if (typeof blob === "string") {
    href = blob;
  // } else {
  //   a.download = filename;
  //   href = URL.createObjectURL(blob);
  // }
  a.href = href;
  a.click();
  URL.revokeObjectURL(href);
}


  

const handleExport = () => {
  if (selectedList.value[0].status == 2 || selectedList.value[0].status == 3) {
    finReportexport({
      id: Id.value
    }).then(() => {
      proxy.$modal.msgSuccess(`导出成功`);
      getListFun()
    })
    window.location.href = selectedList.value[0].url
    // const filename = new Date().valueOf();
    // uploadFile(
    //   selectedList.value[0].status.url,
    //   filename 
    // )
  } else {
    proxy.$modal.msgWarning(`已生成或者已导出的数据才能导出`);
  }


  // 前端大文件分片导出 参考 https://blog.csdn.net/qq_41974199/article/details/127680629
// const DONE = 4;
// const RANGE_SIZE = 100000;
// function getContentLength(url) {
//     return new Promise((resolve, reject) => {
//         var xhr = new XMLHttpRequest();
//         xhr.open('HEAD', url, true);
//         xhr.onreadystatechange = function () {
//           console.log('fa32412351235', xhr)
//             if (xhr.readyState == DONE) {
//                 resolve(xhr.getResponseHeader('Content-Length'));
//             }
//         }
//         xhr.send();
//     })
// }
// function getRangeContent(startIndex, endIndex, url) {
//     return new Promise((resolve, reject) => {
//         var xhr = new XMLHttpRequest();
//         xhr.open('GET', url, true);
//         xhr.setRequestHeader('Range', `bytes=${startIndex}-${endIndex}`);
//         xhr.responseType = 'arraybuffer';
//         xhr.onreadystatechange = function () {
//             if (this.readyState == DONE) {
//                 console.log(this.response)
//                 resolve(this.response);
//             }
//         }
//         xhr.send();
//     })
// }
// function downloadArrayBufferFile(arrayBuffer, fileName) {
//     const blob = new Blob([arrayBuffer], { type: 'application/octet-stream' });
//     const a = document.createElement('a');
//     a.href = URL.createObjectURL(blob);
//     a.download = fileName;
//     a.click();
// }
// function concatArrayBuffer(arrayBufferArray) {
//     let totalLength = 0;
//     arrayBufferArray.forEach(arrayBuffer => {
//         totalLength += arrayBuffer.byteLength;
//     });
//     const result = new Uint8Array(totalLength);
//     let offset = 0;
//     arrayBufferArray.forEach(arrayBuffer => {
//         result.set(new Uint8Array(arrayBuffer), offset);
//         offset += arrayBuffer.byteLength;
//     });
//     return result;
// }
// async function main() {
//     const fileUrl = '/profile/2022/09/30/6b9bc015-dfdd-4fda-b5ce-b5a77d7715ed.jpg';
//     const contentLength = await getContentLength(fileUrl);
//     console.log('dfsaerq', contentLength)
//     const numberRequest = Math.ceil(contentLength / RANGE_SIZE);
//     const arrayBufferArray = [];
//     for (let i = 0; i < numberRequest; i++) {
//         const startIndex = i * RANGE_SIZE;
//         const endIndex = startIndex + RANGE_SIZE - 1;
//         const clip = await getRangeContent(startIndex, endIndex, fileUrl);
//         arrayBufferArray.push(clip);
//     }
//     const result = concatArrayBuffer(arrayBufferArray);
//     downloadArrayBufferFile(result, '715ed.jpg');
// }
// main();
}
agencyListFun()
  drugListFun()
  getprovinceFun()
const submitFormmin = () => {
  getListFun()
}


const handlereport = () => {
  exportHandle(selectedList.value[0]).then(() => {
    proxy.$modal.msgSuccess(`生成成功`);
    getListFun()
  })
}

</script>
<style scoped>
  .app-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 85px);
    overflow: hidden;
  }
  .vex_flex {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
  }
  .flexmin {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
</style>